import requests
import logging
from django.core.cache import cache

logger = logging.getLogger("log")
APPID = "wx6974b8992fd017a9"
SECRET = "4367e73e014c79345c31a0c7dff6555a"


# 获取全新ACCESS_TOKEN
def get_access_token_new():
    result = {"code": 0, "msg": "OK", "data": {}}
    api_name = "获取全新ACCESS_TOKEN"
    logger.info(f"接口>>>{api_name}>>>开始调用")
    url = "https://api.weixin.qq.com/cgi-bin/token"
    url += "?grant_type=client_credential"
    url += "&appid=" + APPID
    url += "&secret=" + SECRET
    try:
        response = requests.get(url)
    except Exception as e:
        print(e)
        logger.error(f"接口>>>{api_name}>>>执行失败>>>未知异常")
        return {"code": 500, "msg": "未知异常"}
    response_json = response.json()
    logger.info(f"接口>>>{api_name}>>>返回结果>>>\n{response_json}")
    try:
        access_token = response_json["access_token"]
        result["data"]["access_token"] = access_token
    except Exception as e:
        print(e)
        logger.error(f"接口>>>{api_name}>>>执行失败>>>未知异常")
        return {"code": 500, "msg": "未知异常"}
    return result


# 获取access_token
def get_access_token():
    api_name = "获取ACCESS_TOKEN"
    logger.info(f"接口>>>{api_name}>>>开始调用")
    if cache.has_key("access_token"):
        access_token = cache.get("access_token")
        api_output = f"1.code<0>; 2.msg<从缓存获取>;"
        logger.info(f"接口>>>{api_name}>>>执行成功>>>\n{api_output}")
        return access_token
    else:
        new_req_res = get_access_token_new()
        if new_req_res["code"] == 0:
            access_token = new_req_res["data"]["access_token"]
            cache.set("access_token", access_token, 7200)
            api_output = f"1.code<0>; 2.msg<重新获取>;"
            logger.info(f"接口>>>{api_name}>>>执行成功>>>\n{api_output}")
            return access_token
        else:
            return False


# 获取OPENID
def get_openid(jscode):
    result = {"code": 0, "msg": "Ok", "data": {}}
    api_name = "获取OPENID"
    logger.info(f"接口>>>{api_name}>>>开始调用")
    url = "https://api.weixin.qq.com/sns/jscode2session"
    url += "?appid=" + APPID
    url += "&secret=" + SECRET
    url += "&js_code=" + jscode
    url += "&grant_type=authorization_code"
    api_input = f"1.jscode<{jscode}>;"
    logger.info(f"接口>>>{api_name}>>>入参>>>{api_input}")
    try:
        response = requests.get(url)
    except Exception as e:
        logger.error(f"接口>>>{api_name}>>>执行失败>>>未知异常")
        ret = {"code": 500, "msg": "未知异常"}
        return ret
    response_json = response.json()
    logger.info(f"接口>>>{api_name}>>>返回结果>>>\n{response_json}")
    try:
        openid = response_json["openid"]
        result["data"]["openid"] = openid
        api_output = f"1.result<{result}>"
        logger.info(f"接口>>>{api_name}>>>执行成功>>>{api_output}")
    except Exception as e:
        logger.error(f"接口>>>{api_name}>>>执行失败>>>获取openid失败")
        ret = {"code": 500, "msg": "获取openid失败"}
        return ret
    return result


# 获取手机号码
def get_weixin_phone(phone_code):
    code = 0
    msg = "Ok"
    data = {}
    api_name = "获取手机号码"
    logger.info(f"接口>>>{api_name}>>>开始调用")
    access_token = get_access_token()
    if not access_token:
        code = 1
        msg = "获取access_token失败"
        api_output = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{api_name}>>>执行失败>>>{api_output}")
        return {"code": code, "msg": msg, "data": data}
    url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
    url += "?access_token=" + access_token
    request_data = {
        "code": phone_code
    }
    api_input = f"1.request_data<{request_data}>;"
    logger.info(f"接口>>>{api_name}>>>入参>>>{api_input}")
    try:
        headers = {
            "Content-Type": "application/json; charset=UTF-8"
        }
        response = requests.post(url,headers=headers,json=request_data)
    except Exception as e:
        code = 500
        msg = "未知异常"
        api_output = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{api_name}>>>执行失败>>>{api_output}")
        ret = {"code": code, "msg": msg, "data": data}
        return ret
    response_json = response.json()
    logger.info(f"接口>>>{api_name}>>>返回结果>>>\n{response_json}")
    errcode = response_json["errcode"]
    if errcode != 0:
        code = response_json["errcode"]
        msg = response_json["errmsg"]
        api_output = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{api_name}>>>执行失败>>>{api_output}")
    else:
        data["phone"] = response_json["phone_info"]["purePhoneNumber"]
        api_output = f"1.code<{code}>;2.msg<{msg}>;"
        logger.info(f"接口>>>{api_name}>>>执行成功>>>{api_output}")
    ret = {"code": code, "msg": msg, "data": data}
    return ret